<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;

class ProfileApiResponse
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if (! $this->canDebug($response)) {
            return $response;
        }

        $debugBar = ['_debugbar' => app('debugbar')->getData()];

        $origin = json_decode($response->getContent(), true) ?? [];
        $content = json_encode($origin + $debugBar);

        $response->setContent($content);

        return $response;
    }

    public function canDebug($response)
    {
        return $response instanceof JsonResponse &&
            app()->bound('debugbar') && app('debugbar')->isEnabled();
    }
}
